package com.briup.store.service.impl;

import com.briup.common.utils.BeanCopyUtils;
import com.briup.store.mapper.CategoryMapper;
import com.briup.store.domain.pojo.Category;
import com.briup.store.service.CategoryService;
import com.briup.store.domain.vo.CategoryGetListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author qinyc
* @description 针对表【es_category(分类表)】的数据库操作Service实现
* @createDate 2024-12-24 09:16:52
*/
@Service
public class CategoryServiceImpl implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryGetListVO> getAllCategory() {
        List<Category> categories = categoryMapper.getAllCategory();

        //扁平化数据转换树状数据
        List<CategoryGetListVO> categoryGetListVOS = BeanCopyUtils.copyBeanList(categories, CategoryGetListVO.class);

        List<CategoryGetListVO> collect = categoryGetListVOS
                .stream()
                .filter(categoryGetListVO -> Objects.isNull(categoryGetListVO.getParentId()))
                .map(
                        (item) -> {
                            item.setChildren(getChildrenData(item, categoryGetListVOS));
                            return item;
                        }).collect(Collectors.toList());

        return collect;
    }


    private List<CategoryGetListVO> getChildrenData(CategoryGetListVO root, List<CategoryGetListVO> all) {
        List<CategoryGetListVO> children = all.stream().filter(subjectVO -> Objects.nonNull(subjectVO.getParentId()))
                .filter(subjectVO ->
                subjectVO.getParentId().equals(root.getId())
        ).map(subjectVO -> {
            subjectVO.setChildren(getChildrenData(subjectVO,all));
            return subjectVO;
        }).collect(Collectors.toList());
        return children;
    }
}




